﻿using iTool.Cloud.Center.Model;
using iTool.Common.Options;
using System;
using System.Threading.Tasks;

namespace iTool.ClusterComponent
{
    public class AdoNetClusterOptions
    {
        /// <summary>
        /// 每次调用超时时间
        /// </summary>
        public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(3);

        /// <summary>
        /// 集群标识
        /// </summary>
        public ClusterIdentificationOptions ClusterOptions { get; set; } = new ClusterIdentificationOptions();

        /// <summary>
        /// 数据库节点
        /// </summary>
        public AdoNetOptions AdoNetOptions { get; set; } = new AdoNetOptions();

        /// <summary>
        /// 端口配置
        /// </summary>
        public EndpointsOptions EndpointsOptions { get; set; } = new EndpointsOptions();

        public async Task CheckDataStructuresAsync()
        {
            var checkHandel = new AdoNetCheckDataStructures(this.AdoNetOptions);

            if (!await checkHandel.CheckDatabaseExistsAsync(this.AdoNetOptions.DatabaseName))
            {
                await checkHandel.CreateDatabaseAsync(this.AdoNetOptions.DatabaseName);
            }

            if (!await checkHandel.CheckTableExistsAsync("OrleansQuery")) 
            {
                await checkHandel.CreateDatabaseStructerAsync();
            }
            else
            {
                // 清理无效的 集群节点
                await checkHandel.ClearNoActiveTimeNoderAsync();
            }

            if (!await checkHandel.CheckDatabaseExistsAsync(this.AdoNetOptions.QueueDatabaseName))
            {
                await checkHandel.CreateDatabaseAsync(this.AdoNetOptions.QueueDatabaseName);
            }


        }
    }
}
